var easemob = sm("do_Easemob");
var app = sm("do_App");
var page = sm("do_Page");
var nf = sm("do_Notification");
var global = sm("do_Global");
var external = sm("do_External");
var imHelper = require("helper/im");
var open = require("helper/open");
var userUtil = require("helper/user");
var time = require("util/time");
var http = require("helper/http");
var httpSilence = require("helper/httpSilence");
var openHelper = require("helper/open");
var imUrl = require("url/im");
var guideHelper = require("helper/guide");
var deviceUtil = require("helper/device");

//渲染页面头部begin
var headerAout = ui("headerAout");
var addheader = headerAout.add("header", "source://view/reuse/header.ui", 0, 0);
//左上角-返回
var headerLeft = ui(addheader+".headerLeft");
headerLeft.on("touch", function() {
	resetAllNewMsgTip();
    app.closePage();
});
ui(addheader+".labelTitle").text = "我的消息";
//右上角--图标【菜单】
var headerRight = ui(addheader + ".headerRight");
var imgNext = ui(addheader + ".imgNext");
imgNext.source = "source://image/common/more.png";
imgNext.visible = true;
//渲染页面头部end

//右上角menu--begin
var menus= [];
menus=[{"template" : 0,"menuIcon":"source://image/menu/gchat.png","menuName":"发起群聊","type":"addGchat"},
       {"template" : 0,"menuIcon":"source://image/menu/users.png","menuName":"我的好友","type":"myFriend"}];
var popmenu = ui("$").add("menupop", "source://view/reuse/menu/menul.ui", 0, 0);
var popmenuf = ui("menupop");
headerRight.on("touch", function() {
	popmenuf.fire("popmenuSJ", menus);
});
popmenuf.on("popmenuItem", function(data) {
	var touchIndex = parseInt(data);
	var actionType = menus[touchIndex].type;
	if(actionType=="addGchat"){
		popmenuf.fire("popmenuClose");
		openHelper.open("source://view/user/friend/create4gchat/create4gchat.ui");//发起群聊
	}else if(actionType=="myFriend"){
		popmenuf.fire("popmenuClose");
		openHelper.open("source://view/user/friend/myFriend.ui");//我的好友
	}
});
//右上角menu--end

//andriod返回键
page.on("back", function() {
	resetAllNewMsgTip();
	app.closePage();
});
//模板序号
/*
source://view/im/message/zan_cell.ui,
source://view/im/message/message_cell.ui,
source://view/im/message/friendApp_cell.ui,
source://view/im/message/circleInvite_cell.ui,
source://view/im/message/circleApply_cell.ui,
source://view/reuse/noCell.ui,
source://view/reuse/slideOper.ui
source://view/im/message/note_cell.ui
*/
var zan_template = 0,message_template = 1,friend_template = 2,
	circleInvite_template = 3,circleApply_template = 4,blank_template = 5,
	slideOper_template = 6,note_template = 7;
var noData = [{"template":blank_template,"labelContent":"没有消息"}];

var conversationId, type, timestamp, lastMessage;

var listdata = mm("do_ListData");
var listview = ui("slideListView");//带左滑功能
listview.bindItems(listdata);
listview.refreshItems();

//页面加载后，查询历史消息
var myImId = null;
var myNick = null;
page.on("loaded", function(data, e) {
	getMyInfo();
	getImHistory();
	getOtherMessage(true);//静默请求后台
	//订阅 -收到新消息【统一在/helper/im 调用addMsgListener进行监听
	app.on("im_comming_messages4msg", function(data) {
		showComingMessage(data);
	})
});

function getMyInfo() {
	imHelper.loadMe(function(myImUser) {
		myImId = myImUser.imId;
		myNick = myImUser.name;
	})
}

//订阅-我发送的最新消息
app.on("im_sending_messages", function(data) {
	showSendingMessage(data);
})

//订阅 -退出或解散群聊
app.on("fire_quit_or_dismiss_groupchat", function(imGroupId) {
	for (var i = 0; i < listdata.getCount(); i++) {
		var oneData = listdata.getOne(i);
		if (oneData.type=="GroupChat" && oneData.imId == imGroupId) {
			listdata.removeData([i]);
			listview.refreshItems();
			break;
		}
	}
})
//处理 好友申请后-删除列表中的好友申请消息
page.on("message_reflash_friend", function(friendApplyId) {
	for (var i = 0; i < listdata.getCount(); i++) {
		var oneData = listdata.getOne(i);
		if (oneData.type=="friend" && oneData.bussId == friendApplyId) {
			listdata.removeData([i]);
			listview.refreshItems();
			break;
		}
	}
})

//处理 圈子邀请后-删除列表中的圈子邀请消息
page.on("message_reflash_circle_invite", function(circleInviteId) {
	for (var i = 0; i < listdata.getCount(); i++) {
		var oneData = listdata.getOne(i);
		if (oneData.type=="circleInvite" && oneData.bussId == circleInviteId) {
			listdata.removeData([i]);
			listview.refreshItems();
			break;
		}
	}
})

//处理 圈子申请后-删除列表中的圈子申请消息
page.on("message_reflash_circle_apply", function(circleApplyId) {
	for (var i = 0; i < listdata.getCount(); i++) {
		var oneData = listdata.getOne(i);
		if (oneData.type=="circleApply" && oneData.bussId == circleApplyId) {
			listdata.removeData([i]);
			listview.refreshItems();
			break;
		}
	}
})

//处理 删除"评论消息"
page.on("message_delete_comment_row", function(data) {
	removeNewCommentTip();
})

//处理 删除"点赞消息"
page.on("message_delete_zan_row", function(data) {
	removeNewZanTip();
})

//处理 删除"一条单聊"
page.on("message_delete_Chat_row", function(imId) {
	removeImConversation(imId);
})

//处理 删除"一条群聊"
page.on("message_delete_GroupChat_row", function(imId) {
	removeImConversation(imId);
})

//删除列表中的后台推送消息
page.on("message_delete_adminPush_row", function(pushMsgId) {
	for (var i = 0; i < listdata.getCount(); i++) {
		var oneData = listdata.getOne(i);
		if (oneData.type=="adminPush" && oneData.bussId == pushMsgId) {
			listdata.removeData([i]);
			listview.refreshItems();
			break;
		}
	}
})

//从对话页面返回
/**
 * data: {
 * chat_back: true 或 false,
 * chat_type: Chart 或 GroupChat,
 * chat_to: imId
 * }
 */
page.on("result", function(data){
	if (data.chat_back && data.chat_to !=null) {
		clearImNewMsgTip({imId:data.chat_to});
		resetAllNewMsgTip();
    }
	if (data.dismissGroup || data.quitGroup) {
		
    }
});


app.on("closeChatPage", function(data){
	if (data.chat_close && data.chat_to !=null) {
		clearImNewMsgTip({imId:data.chat_to});
		resetAllNewMsgTip();
    }
});

//下拉刷新页面
listview.on("pull", function(data, e) {
	if (data.state == 2) {
		removeOtherMessage();//清除【除IM消息之外的其他信息】
		getOtherMessage(false);
		listview.rebound();//复位【一定要做】
	}
})
//上拉列表，翻页数据
listview.on("push", function(data){
	if (data.state == 2){
		listview.rebound();//复位【一定要做】
	}
});

listview.on("touch", "", 3000, function(data) {
	var oneMsg = listdata.getOne(data);
	var bussId = oneMsg.bussId;//userId或groupId
	var type = oneMsg.type;//Chat或GroupChat
	if(type == "Chat"){
		clearImNewMsgTip(oneMsg);//去掉小红点（数量）
		imHelper.toChat(bussId);
	}else if(type == "GroupChat"){
		clearImNewMsgTip(oneMsg);//去掉小红点（数量）
		imHelper.toGroupChat(bussId);
	}else if(type == "comment"){//评论
		var newCommentCount = imHelper.getUnReadCount2Her({herId:"comment"});
		open.open("source://view/public/comment/manage/comment2me.ui",{"count":newCommentCount});
		removeNewCommentTip();
	}else if(type == "zan"){//点赞
		var newZanCount = imHelper.getUnReadCount2Her({herId:"zan"});
		open.open("source://view/public/praise/manage/praise2me.ui",{"count":newZanCount});
		removeNewZanTip();
	}else if(type == "adminPush"){//后台推送
		var url = oneMsg.url;
		if(url != null && url!="" && url !="undefined"){
			if(url.indexOf("http://") >=0 ){
				external.openURL(url);
			}else if(url.indexOf("source://") >=0){
				var paraJson = {};
				//deviceone.print(url,"url")
				var mainUrl = url;
				if(url.indexOf("?") >0){
					mainUrl = url.substring(0,url.indexOf("?"));//主URL没有参数
					var paramStr = url.substring(url.indexOf("?")+1, url.length);//参数部份，如【id=32&name=小明】
					//deviceone.print(paramStr,"paramStr")
					var paramList = paramStr.split("&");
					for(var i=0;i<paramList.length;i++){
						paraJson[paramList[i].split("=")[0]] = paramList[i].split("=")[1];
					}
				}
				//deviceone.print(JSON.stringify(paraJson))
				open.open(mainUrl,paraJson);//打开链接
			}
		}
	}
	resetAllNewMsgTip();
});

//清除一行数据的“新消息数量”红点
function clearImNewMsgTip(imMessage){
	if(imMessage!=null && imMessage.imId!=null){
		for (var i = 0; i < listdata.getCount(); i++) {
			var oneData = listdata.getOne(i);
			if (oneData.imId==imMessage.imId) {
				imHelper.clearUnReadCount2Her({herId:oneData.imId});
				imHelper.reduceMyUnReadCount({reduceCount:oneData.newMsgCount});//减少我的未读消息数量
				oneData.newMsgCount = 0;
				oneData.showNewMsgTip = false;
				listdata.updateOne(i, oneData);
				listview.refreshItems();
				
				break;
			}
		}
	}
}


//按时间倒序排序
function down(x, y) {
    return (x.timestamp < y.timestamp) ? 1 : -1
}

//显示收的对方的消息
function showComingMessage(data){
	var messageId = data.messageId;
	if(isMessageExists(messageId)){
		return;
	}
	var unReadCount = 0;//未读消息数量
	var isExitInPage= false;//页面中是否存在这个用户或群组
	var from = data.from;
	var to = data.to;
	var chatType = data.chatType;
	var body_text = data.body.text;
	var body_type = data.body.type;//0.Text(文本),1.Image(图片),2.Location(位置),3.Voice(语音),4.Video(视频),5.File(文件)
	timestamp = time.shortFormat(data.timestamp);//时间格式化
	if(body_type=="0"){
		if(body_text.indexOf("GroupChatTip:")>-1){
			body_text = body_text.replace("GroupChatTip:","");//群聊邀请去掉“关键字”
			if(body_text.indexOf("邀请")>-1 || body_text.indexOf("退出")>-1 || body_text.indexOf("解散")>-1){
				if(body_text.indexOf(myNick)==1){
					//如果是我发起群聊邀请、我退出群聊、我解散群聊，不显示在我的消息列表
					return;
				}
			}else if(body_text.indexOf("被移出")>-1){
				if(body_text.indexOf(myNick)==1){
					//如果是我被移出群聊，显示【你已被移出该群聊】
					body_text = "你已被移出该群聊";
				}
			}
		}
	}else if(body_type=="1"){
		body_text = "[图片]"; 
	}else if(body_type=="2"){
		body_text = "[位置]"; 
	}else if(body_type=="3"){
		body_text = "[语音]"; 
		imHelper.storeUnReadAudioIds(messageId);//缓存未读语音messageId
	}else if(body_type=="4"){
		body_text = "[视频]"; 
	}else if(body_type=="5"){
		body_text = "[文件]";
	}
	if (chatType == "Chat") {//单聊
		for (var i = 0; i < listdata.getCount(); i++) {
			var oneData = listdata.getOne(i);
			if (oneData.imId==from) {//如果页面中有这个用户的消息
				isExitInPage = true;
				oneData.last= body_text;//更新内容
				oneData.time = timestamp;//更新时间
				oneData.newMsgCount = oneData.newMsgCount+1;//新消息数量+1
				oneData.showNewMsgTip = true;//显示消息数量
				oneData.messageId = messageId;
				listdata.removeData([i]);//删除它
				listdata.addOne(oneData,0);//搬到首行
				listview.refreshItems();
				break
			}
		}
		if(!isExitInPage){
			imHelper.loadUserByImId(from,function(imUser){
				listdata.addOne({
					"template" : message_template,//使用“消息”模板
					"rightTemplate" : slideOper_template,
					"logo" : imUser.logo,
					"imId" : imUser.imId,
					"bussId" : imUser.userId,
					"name" : imUser.name,						
					"last" : body_text,
					"time" : timestamp,
					"type" : chatType,
					"newMsgCount" : 1,
					"showNewMsgTip" : true,
					"messageId" : messageId
				},0);
				listview.refreshItems();
			})
		}
	
	}else{//群聊
		for (var i = 0; i < listdata.getCount(); i++) {
			var oneData = listdata.getOne(i);
			if (oneData.imId==to) {//如果页面中有这个群的消息
				isExitInPage = true;
				oneData.last=body_text;//更新内容
				oneData.time = timestamp;//更新时间
				oneData.newMsgCount = oneData.newMsgCount+1;//新消息数量+1
				oneData.showNewMsgTip = true;//显示消息数量
				oneData.messageId = messageId;
				listdata.removeData([i]);//删除它
				listdata.addOne(oneData,0);//搬到首行
				listview.refreshItems();
				break
			}
		}
		if(!isExitInPage){
			imHelper.loadGroupByImId(to,function(imGroup){
				listdata.addOne({
					"template" : message_template,//使用“消息”模板
					"rightTemplate" : slideOper_template,
					"logo" : imGroup.logo,
					"isCircle": imGroup.isCircle,
					"imgItems": imGroup.imgItems,
					"imId" : imGroup.imId,
					"bussId" : imGroup.groupId,//圈子id
					"name" : imGroup.name,						
					"last" : body_text,
					"time" : timestamp,
					"type" : chatType,
					"newMsgCount" : 1,
					"showNewMsgTip" : true,
					"messageId" : messageId
				},0);
				listview.refreshItems();
			})
		}
	}
}

//显示我发的消息
function showSendingMessage(data){
	var isExitInPage= false;//页面中是否存在这个用户或群组
	var from = data.from;
	var to = data.to;
	var chatType = data.chatType;
	var body_text = data.body.text;
	var body_type = data.body.type;//0.Text(文本),1.Image(图片),2.Location(位置),3.Voice(语音),4.Video(视频),5.File(文件)
	timestamp = time.shortFormat(data.timestamp);//时间格式化
	if(body_type=="1"){
		body_text = "[图片]"; 
	}else if(body_type=="2"){
		body_text = "[位置]"; 
	}else if(body_type=="3"){
		body_text = "[语音]"; 
	}else if(body_type=="4"){
		body_text = "[视频]"; 
	}else if(body_type=="5"){
		body_text = "[文件]";
	}
	if (chatType == "Chat") {//单聊
		for (var i = 0; i < listdata.getCount(); i++) {
			var oneData = listdata.getOne(i);
			if (oneData.imId==to) {//如果页面中有这个用户的消息
				isExitInPage = true;
				oneData.last= body_text;//更新内容
				oneData.time = timestamp;//更新时间
				//oneData.newMsgCount = oneData.newMsgCount+1;//新消息数量+1
				oneData.showNewMsgTip = false;//不显示消息数量
				oneData.messageId = new Date().getTime();
				listdata.removeData([i]);//删除它
				listdata.addOne(oneData,0);//搬到首行
				listview.refreshItems();
				break
			}
		}
		if(!isExitInPage){
			imHelper.loadUserByImId(to,function(imUser){
				listdata.addOne({
					"template" : message_template,//使用“消息”模板
					"rightTemplate" : slideOper_template,
					"logo" : imUser.logo,
					"imId" : imUser.imId,
					"bussId" : imUser.userId,
					"name" : imUser.name,						
					"last" : body_text,
					"time" : timestamp,
					"type" : chatType,
					"newMsgCount" : 0,
					"showNewMsgTip" : false,
					"messageId" : new Date().getTime()
				},0);
				listview.refreshItems();
			})
		}
	
	}else{//群聊
		for (var i = 0; i < listdata.getCount(); i++) {
			var oneData = listdata.getOne(i);
			if (oneData.imId==to) {//如果页面中有这个群的消息
				isExitInPage = true;
				oneData.last=body_text;//更新内容
				oneData.time = timestamp;//更新时间
				//oneData.newMsgCount = oneData.newMsgCount+1;//新消息数量+1
				oneData.showNewMsgTip = false;//不显示消息数量
				oneData.messageId = new Date().getTime();
				listdata.removeData([i]);//删除它
				listdata.addOne(oneData,0);//搬到首行
				listview.refreshItems();
				break
			}
		}
		if(!isExitInPage){
			imHelper.loadGroupByImId(to,function(imGroup){
				listdata.addOne({
					"template" : message_template,//使用“消息”模板
					"rightTemplate" : slideOper_template,
					"logo" : imGroup.logo,
					"isCircle": imGroup.isCircle,
					"imgItems": imGroup.imgItems,
					"imId" : imGroup.imId,
					"bussId" : imGroup.groupId,//圈子id
					"name" : imGroup.name,						
					"last" : body_text,
					"time" : timestamp,
					"type" : chatType,
					"newMsgCount" : 0,
					"showNewMsgTip" : false,
					"messageId" : new Date().getTime()
				},0);
				listview.refreshItems();
			})
		}
	}
}

//判断消息是否存在（根据messageId）
function isMessageExists(vsMessageId){
	//deviceone.print(vsMessageId);
	var isExists = false;
	for (var i = 0; i < listdata.getCount(); i++) {
		var oneData = listdata.getOne(i);
		if (oneData.messageId==vsMessageId) {//如果页面中有这条消息
			isExists = true;
			break;
		}
	}
	return isExists;
}

/**
 * 增加新的“点赞”数量
 * @param newCount
 * @param refreshPage 是否刷新页面
 * @returns
 */
function addNewPraise2me(newCount,refreshPage){
	if(newCount<=0 || newCount=="" || newCount ==="undefined"){
		return;
	}
	var oneData = null;
	var isExists = false;
	for (var i = 0; i < listdata.getCount(); i++) {
		oneData = listdata.getOne(i);
		if (oneData.type=="zan") {
			isExists = true;
			oneData.newZanCount = oneData.newZanCount + newCount;//增加数量
			oneData.showZanTip = true;
			listdata.updateOne(i, oneData);
			if(refreshPage){
				listview.refreshItems();
			}
			break;
		}
	}
	if(!isExists){
		listdata.addOne({
			"template" : zan_template,//使用“点赞”模板
			"rightTemplate" : slideOper_template,
			"logo" : "source://image/im/zan.png",
			"imId" : "",
			"bussId" : "",
			"name" : "赞",						
			"last" : "",
			"time" : "",
			"type" : "zan",
			"newZanCount" : newCount,
			"showZanTip" : true
		},0);
		if(refreshPage){
			listview.refreshItems();
		}
	}
}

//消失显示新的“点赞”数量(用于点击了“点赞”操作)
function removeNewZanTip(){
	var oneData = null;
	for (var i = 0; i < listdata.getCount(); i++) {
		oneData = listdata.getOne(i);
		if (oneData.type=="zan") {
			listdata.removeData([i]);
			listview.refreshItems();
			imHelper.clearUnReadCount2Her({herId:"zan"});
			imHelper.reduceMyUnReadCount({reduceCount:imHelper.getUnReadCount2Her({herId:"zan"})});//减少我的未读消息数量
			break;
		}
	}
}

/**
 * 增加新的"评论"数量
 * @param newCount
 * @param refreshPage 是否刷新页面
 * @returns
 */
function addNewComment2me(newCount,refreshPage){
	if(newCount<=0 || newCount=="" || newCount ==="undefined"){
		return;
	}
	var oneData = null;
	var isExists = false;
	for (var i = 0; i < listdata.getCount(); i++) {
		oneData = listdata.getOne(i);
		if (oneData.type=="comment") {
			isExists = true;
			oneData.newZanCount = oneData.newZanCount + newCount;//增加数量
			oneData.showZanTip = true;
			listdata.updateOne(i, oneData);
			if(refreshPage){
				listview.refreshItems();
			}
			break;
		}
	}
	if(!isExists){
		listdata.addOne({
			"template" : zan_template,//使用“评论”模板
			"rightTemplate" : slideOper_template,
			"logo" : "source://image/im/ping.png",
			"imId" : "",
			"bussId" : "",
			"name" : "评论",						
			"last" : "",
			"time" : "",
			"type" : "comment",
			"newZanCount" : newCount,
			"showZanTip" : true
		},0);
		if(refreshPage){
			listview.refreshItems();
		}
	}
}

//消失显示新的“评论”数量(用于点击了“评论”操作)
function removeNewCommentTip(){
	var oneData = null;
	for (var i = 0; i < listdata.getCount(); i++) {
		oneData = listdata.getOne(i);
		if (oneData.type=="comment") {
			listdata.removeData([i]);
			listview.refreshItems();
			imHelper.clearUnReadCount2Her({herId:"comment"});
			imHelper.reduceMyUnReadCount({reduceCount:imHelper.getUnReadCount2Her({herId:"comment"})});//减少我的未读消息数量
			break;
		}
	}
}

/**
 * 后台查询消息--点赞我的、评论我的、好友申请、圈子邀请我加入、申请加入我的圈子
 * 置顶显示
 */
var httpHandler = http;
function getOtherMessage(isSilence){
	var hasOtherMsg = false;//是否有其他的消息
	if(userUtil.loginToken()==""){
		return;
	}
	if(isSilence){
		httpHandler = httpSilence;
	}else{
		httpHandler = http;
	}
	var unReadMsgCount = 0;//未读消息数量
	var showNewMsgTip = false;
	
	var commentCount = imHelper.getUnReadCount2Her({herId:"comment"});//取缓存中【评论我的数量】
	if(commentCount>0){
		addNewComment2me(commentCount,false);
		hasOtherMsg = true;
	}
	var zanCount = imHelper.getUnReadCount2Her({herId:"zan"});//取缓存中【点赞我的数量】
	if(zanCount>0){
		addNewPraise2me(zanCount,false);
		hasOtherMsg = true;
	}
	
	//官方公告
	var adminPushList = imHelper.getAdminPushCahce();
	for(var i in adminPushList){
		listdata.addOne({
			"template" : note_template,//使用“官方公告”模板
			"rightTemplate" : slideOper_template,
			"imId" : "",
			"bussId" : adminPushList[i].msgId,
			"title" : adminPushList[i].title,
			"content" : adminPushList[i].content,
			"url" : adminPushList[i].url,
			"time" : time.shortFormat(adminPushList[i].time),
			"type" : "adminPush"
		},0);
	}
	
	
	httpHandler.post(imUrl.url.message.getOtherMessage, {}, function(data) {
		var friendApplyList= data.friendApplyList;
		var circleInviteList  = data.circleInviteList;
		var circleApplyList = data.circleApplyList;
		if(friendApplyList && friendApplyList.length>0){//查询好友申请记录
			hasOtherMsg = true;
			for(var i in friendApplyList){
				listdata.addOne({
					"template" : friend_template,//使用“好友申请”模板
					"rightTemplate" : slideOper_template,
					"logo" : friendApplyList[i].fullUserLogo,
					"imId" : "",
					"userId" : friendApplyList[i].userId,
					"bussId" : friendApplyList[i].id,
					"name" : friendApplyList[i].userName,						
					"last" : friendApplyList[i].message,
					"time" : friendApplyList[i].cnNewAt,
					"type" : "friend"
				},0);
			}
		}
		if(circleInviteList  && circleInviteList.length>0){//查询圈子邀请记录
			hasOtherMsg = true;
			for(var i in circleInviteList){
				listdata.addOne({
					"template" : circleInvite_template,//使用“圈子邀请”模板
					"rightTemplate" : slideOper_template,
					"logo" : circleInviteList[i].fullInviterImg,
					"imId" : "",
					"bussId" : circleInviteList[i].id,
					"name" : circleInviteList[i].inviterName,						
					"last" : "",
					"time" : circleInviteList[i].cnNewAt,
					"type" : "circleInvite",
					"circleId": circleInviteList[i].circleId,
					"circleName": circleInviteList[i].circleName,
					"userId":circleInviteList[i].inviterId
				},0);
			}
		}
		if(circleApplyList  && circleApplyList.length>0){//查询圈子申请加入记录
			hasOtherMsg = true;
			for(var i in circleApplyList){
				listdata.addOne({
					"template" : circleApply_template,//使用“圈子申请”模板
					"rightTemplate" : slideOper_template,
					"logo" : circleApplyList[i].fullApplyerImg,
					"imId" : "",
					"bussId" : circleApplyList[i].id,
					"name" : circleApplyList[i].applyerName,						
					"last" : "",
					"time" : circleApplyList[i].cnNewAt,
					"type" : "circleApply",
					"circleId": circleApplyList[i].circleId,
					"circleName": circleApplyList[i].circleName,
					"userId":circleApplyList[i].applyerId
				},0);
			}
		}
		if(hasOtherMsg){
			//如果有其他的消息，刷新列表
			listview.refreshItems();
		}
	});
}

//清除【除IM消息之外的其他信息】
function removeOtherMessage() {
	for (var i = 0; i < listdata.getCount(); i++) {
		var oneData = listdata.getOne(i);
		if (oneData.type!="Chat" && oneData.type!="GroupChat") {
			listdata.removeData([i]);
			listview.refreshItems();
		}
	}
}

/**
 * 查询历史消息
 * easemob.getAllConversations
 * 获取会话列表是一个数组，
 * 返回值包括[{"conversationId":"是一个枚举，包括IM用户名username（单聊）、groupID（群聊）",
 * "type":"是一个枚举，包括单聊(Chat)，群聊(GroupChat)","timestamp":"最后一条消息的时间戳",
 * "lastMessage":"最后一条消息，当消息为文本时则显示消息内容；
 * 若为定位消息则显示[定位]；若为图片消息则显示[图片]；若为语音消息则显示[语音]；若为音频消息则显示[音频]；若为文件消息则显示[文件]"}]
 */
function getImHistory() {
	easemob.getAllConversations(function(data, e) {
		if(data.length==0){
			return;
		}
		data.sort(down);//按时间倒序排序
		var msg =null;
		for (var i = 0; i < data.length; i++) {
			msg= data[i];
			type = msg.type;
			conversationId = msg.conversationId;
			var deleteMsgTime = imHelper.getOurMessageTime({herId:conversationId});
			if(msg.timestamp > deleteMsgTime){
				timestamp = time.shortFormat(msg.timestamp);//时间格式化
				lastMessage = msg.lastMessage;
				if(type=="GroupChat"){
					if(lastMessage.indexOf("GroupChatTip:")>-1){
						lastMessage = lastMessage.replace("GroupChatTip:","");//群聊邀请去掉“关键字”
						if(lastMessage.indexOf("退出")>-1 || lastMessage.indexOf("解散")>-1){
							if(lastMessage.indexOf(myNick)==1){
								//如果是我退出群聊、我解散群聊，不显示在我的消息列表
								continue;
							}
						}else if(lastMessage.indexOf("被移出")>-1){
							if(lastMessage.indexOf(myNick)==1){
								//如果是我被移出群聊，显示【你已被移出该群聊】
								lastMessage = "你已被移出该群聊";
							}
						}
					}
				}
				if(lastMessage=="[音频]"){//IOS固定返回，这里手动改一下
					lastMessage = "[语音]";
				}
				listdata.addOne({//先加上一条消息【只有内容+时间，没有头象、名称、消息红点】
					"template" : message_template,//使用“消息”模板
					"rightTemplate" : slideOper_template,
					"logo" : "",
					"imId" : conversationId,
					"bussId" : "",
					"name" : "",						
					"last" : lastMessage,
					"time" : timestamp,
					"type" : type,
					"newMsgCount" : 0,
					"showNewMsgTip" : false
				});
				fixLogoNameTips4Message(conversationId,true);//补充：用户或群组的id、头象和名称及消息红点
			}
		}
		listview.refreshItems();
	})
}

/**
 * 为某条消息渲染用户或群组的id、头象和名称及消息红点
 * @param vsImId
 * @param isRefreshItems 是否马上刷新列表
 * @returns
 */
function fixLogoNameTips4Message(vsImId,isRefreshItems){
	for (var i = 0; i < listdata.getCount(); i++) {
		var oneData = listdata.getOne(i);
		if (oneData.imId==vsImId) {//如果页面中有这条消息
			if (oneData.type == "Chat") {
				imHelper.loadUserByImId(oneData.imId,function(imUser){
					unReadMsgCount = imHelper.getUnReadCount2Her({herId:imUser.imId});
					oneData.newMsgCount = unReadMsgCount;
					oneData.showNewMsgTip = (unReadMsgCount > 0 ? true : false);
					oneData.bussId = imUser.userId;
					oneData.logo = imUser.logo;
					oneData.name = imUser.name;
					listdata.updateOne(i, oneData);
					if(isRefreshItems){
						listview.refreshItems();
					}
				})
			}else if(oneData.type == "GroupChat"){
				imHelper.loadGroupByImId(oneData.imId,function(imGroup){
					unReadMsgCount = imHelper.getUnReadCount2Her({herId:imGroup.imId});
					oneData.newMsgCount = unReadMsgCount;
					oneData.showNewMsgTip = (unReadMsgCount > 0 ? true : false);
					oneData.bussId = imGroup.groupId;
					oneData.logo = imGroup.logo;
					oneData.name = imGroup.name;
					oneData.isCircle = imGroup.isCircle;
					oneData.imgItems = imGroup.imgItems;
					listdata.updateOne(i, oneData);
					if(isRefreshItems){
						listview.refreshItems();
					}
				})
			}
			break;
		}
	}
}

/**
 * 删除会话（聊天记录）
 * @param imId
 */
function removeImConversation(vsImId){
	imHelper.setOurMessageTime({herId:vsImId});//记录删除时间
	easemob.deleteConversation([vsImId],function(data){
		deviceone.print(JSON.stringify(data),"IM删除会话回调")
	});
	//删除页面中的记录
	for (var i = 0; i < listdata.getCount(); i++) {
		var oneData = listdata.getOne(i);
		if (oneData.imId==vsImId) {//如果页面中有这个用户的消息
			imHelper.clearUnReadCount2Her({herId:vsImId});
			imHelper.reduceMyUnReadCount({reduceCount:oneData.newMsgCount});//减少我的未读消息数量
			listdata.removeData([i]);
			listview.refreshItems();
			break
		}
	}
}

//重新统计页面中未读消息数量
function resetAllNewMsgTip(){
	var newTipCount = 0;
	var oneData = null;
	for (var i = 0; i < listdata.getCount(); i++) {
		oneData = listdata.getOne(i);
		if (oneData.showNewMsgTip) {
			newTipCount ++;
		}
	}
	if(newTipCount == 0){
		imHelper.clearMyUnReadCount();//清零【我的未读消息数量】
	}
}
